package cn.ubeta.b2c.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import cn.ubeta.b2c.BuildConfig;
import cn.ubeta.b2c.common.LoginCommon;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by denny on 16/4/3.
 */
public class NetworkHelper {

    private static OkHttpClient okHttpClient = null;

    /**
     * 调用网络请求
     * @param url
     * @param cb
     */
    public static void call(String url, final NetworkCallback cb) {
        call(null, Constants.SERVER_HOST + url, cb);
    }

    /**
     * 调用网络请求(外部网络请求,非预定的域名)
     * @param url
     * @param cb
     */
    public static void callExternal(String url, final NetworkCallback cb) {
        call(null, Constants.SERVER_HOST + url, cb);
    }

    /**
     * 调用网络请求
     * @param context 是否等待进度条
     * @param url
     * @param cb
     */
    public static void call(final Context context, String url, final NetworkCallback cb) {
        if (okHttpClient == null)
            okHttpClient = new OkHttpClient();

        // 追加通用参数
        StringBuilder sb = new StringBuilder("https://" + url);
        sb.append(url.contains("?") ? "&" : "?");
        // 渠道标识
        sb.append("app_channel=").append(AppInfo.getAppChannel());
        // 版本号
        sb.append("&app_ver=").append(BuildConfig.VERSION_NAME);
        // 版本code
        sb.append("&app_ver_code=").append(String.valueOf(BuildConfig.VERSION_CODE));
        // uid
        if (LoginCommon.isLogin())
            sb.append("&uid=").append(AppConfig.getUid());
        //sb.append("&token=").append(AppConfig.getToken());

        Request request = new Request.Builder().url(sb.toString()).build();

        // 是否有等待进度条
        final ProgressDialog progressDialog = context != null ? new ProgressDialog(context) : null;
        if (progressDialog != null) {
            progressDialog.setMessage("请稍等");
            progressDialog.show();
        }

        okHttpClient.newCall(request).enqueue(new Callback() {

            Handler handler = new Handler(Looper.getMainLooper());

            @Override
            public void onFailure(Request request, final IOException e) {
                handler.post(() -> {
                    if (progressDialog != null)
                        progressDialog.dismiss();
                    cb.onFailure(e);
                });
            }

            @Override
            public void onResponse(final Response response) throws IOException {
                final String bodyString = response.body().string();
                handler.post(() -> {
                    if (progressDialog != null)
                        progressDialog.dismiss();

                    Dlog.e("NetworkHelper : " + request.urlString() + "\n" + bodyString);

                    Object objResp = null;
                    try {
                        objResp = new Gson().fromJson(bodyString, cb.getType());
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    cb.onResponse(objResp);
                });
            }
        });
    }

    /**
     * 当前是否WIFI网络
     * @return
     */
    public static boolean isWifi(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI;
    }

    /**
     * 下载文件
     */
    public static void downloadFile(String url, String fileName, NetworkCallback cb) {
        if (okHttpClient == null)
            okHttpClient = new OkHttpClient();

        Request request = new Request.Builder().url(url).build();

        okHttpClient.newCall(request).enqueue(new Callback() {

            Handler handler = new Handler(Looper.getMainLooper());

            @Override
            public void onFailure(Request request, final IOException e) {
                handler.post(() -> {
                    cb.onFailure(e);
                });
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String filePathName = saveFile(response, fileName);
                handler.post(() -> {
                    Dlog.e("NetworkHelper : Download finished : " + fileName + ", " + filePathName);
                    cb.onResponse(filePathName);
                });
            }
        });
    }

    /**
     * 保存文件
     * @return
     */
    private static String saveFile(Response response, String filePathName) {
        InputStream is = null;
        byte[] buf = new byte[2048];
        int len;
        FileOutputStream fos = null;
        try {
            is = response.body().byteStream();
            //final long total = response.body().contentLength();
            //long sum = 0;

            File file = new File(filePathName);
            File dir = new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("/")));
            if (!dir.exists()) {
                dir.mkdirs();
            }

            fos = new FileOutputStream(file);
            while ((len = is.read(buf)) != -1) {
                //sum += len;
                fos.write(buf, 0, len);
                // TODO 下载进度
            }
            fos.flush();

            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException e) {
            }
            try {
                if (fos != null) fos.close();
            } catch (IOException e) {
            }
        }

        return null;
    }
}
